package com.guo.pet_store.controller;

import com.guo.pet_store.admin.pojo.Pet;
import com.guo.pet_store.admin.service.PetService;
import com.guo.pet_store.admin.service.SearchService;
import com.guo.pet_store.admin.service.TypeService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @Autowired
    private PetService petService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private SearchService searchService;
    @RequestMapping("/index")
    public String getIndex(Model model, HttpSession session){
        model.addAttribute("user",session.getAttribute("user"));
        model.addAttribute("pets",petService.listPetsOnSale());
        model.addAttribute("types",typeService.parentType());
        model.addAttribute("index",-1);
        return "index";
    }
//实现自动补全的代码
    @ResponseBody
    @RequestMapping("/autoSearch")
    public Map autoSearch(String content){
        System.out.println("进入了autoSearch");
        System.out.println("搜索内容是"+content);
        HashMap<String, List> map = new HashMap<>();
        map.put("message",searchService.autoSearch(content));
        System.out.println(searchService.autoSearch(content));
        return map;
    }
    @RequestMapping("/index/{id}")
    public String getPetsByType(Model model,@PathVariable Long id,HttpSession session){
        model.addAttribute("user",session.getAttribute("user"));
        //如果是父id
        if(typeService.getAPetType(id).getParent()){
            model.addAttribute("types",typeService.sonType(id));
            model.addAttribute("pets",petService.petsByParentType(id));
        }else { //如果是子id
            //仍然返回子id目录
            model.addAttribute("types",typeService.sonType(typeService.getAPetType(id).getParentId()));
            model.addAttribute("pets",petService.getPetsByType(id));
        }
        model.addAttribute("index",id);
        return "index";
    }

    @RequestMapping("/search")
    public String search(@RequestParam String search,Model model,HttpSession session){
        String likeSearch= '%'+search+ '%';
        model.addAttribute("pets",petService.searchPets(search,likeSearch));
        model.addAttribute("user",session.getAttribute("user"));
        model.addAttribute("types",typeService.listType());
        model.addAttribute("index",-1);
        return "index";

    }
}
